/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.menosehmais.framework.security;

import br.com.caelum.vraptor.ioc.Component;
import br.com.menosehmais.framework.business.IBusinessObject;
import br.com.menosehmais.framework.persistence.Id;
import br.com.menosehmais.framework.util.Hash;
import br.com.menosehmais.framework.util.StringUtil;
import br.com.menosehmais.model.ContaDO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Rafael Quintino
 */
@Component
public class SecurityBO implements IBusinessObject {
    
    protected final SecurityDAO securityDAO;
    
    public SecurityBO(SecurityDAO securityDAO) {
        this.securityDAO = securityDAO;
    }
    
    private ContaDO authenticate(String usuario, String senha) {
        if(usuario == null || usuario.isEmpty() || senha == null || senha.isEmpty()) {
            throw new IllegalArgumentException();
        }
        
        byte digest[] = Hash.generateDigest(Hash.Algorithm.SHA, senha);
        String encryptedPassword = StringUtil.toHexaString(digest);
        ContaDO account = securityDAO.findPermitedAccount(usuario, encryptedPassword);
        //inserir login no banco.
        
        return account;
    }
    
    public boolean login(HttpServletRequest request, UserSession userSession, LoginDTO loginDTO) {
        if(request == null || userSession == null || loginDTO == null) {
            return false;
        }
        
        //String remoteAddr = request.getRemoteAddr();
        //String requestedSessionId = request.getRequestedSessionId();
        
        if(userSession.isLogged()){//Verificar no banco tbm!
            logout(userSession);
        }
        
        ContaDO account = authenticate(loginDTO.getUsuario(), loginDTO.getSenha());
        HttpSession session = request.getSession();
        AccountInfo accountInfo = new AccountInfo(account, session.getId());
        
        return userSession.login(accountInfo);

    }
    
    public void logout(UserSession userSession) {
        if(userSession == null) {
            return;
        }
        //remover login do banco.
        userSession.logout();
    }
    
    ////////////////////////////////////////////////////
    
    public void createUser(){
        
    }
    
    public void askToResetPassword(String usuario){
        //...
    }
    
    public void resetPassword(Id id, String oldEncryptedPassword){
        //...
    }
    
    public void login(LoginDTO login){
        //login
    }
    
}
